﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-01 15:08
    /// 描 述：数据字典
    /// </summary>
    public class ec_dataitemBLL : ec_dataitemIBLL
    {
        private ec_dataitemService ec_dataitemService = new ec_dataitemService();

        #region 获取数据
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="isEnabled">是否只取有效</param>
        /// <returns></returns>
        public IEnumerable<ec_dataitemEntity> GetList(string queryJson, bool isEnabled = true, Pagination pagination = null)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var tableName = TableName<ec_dataitemEntity>(queryParam["ProjectId"]?.ToString());
                var keyword = queryParam["keyword"]?.ToString();
                var query = Db.Queryable<ec_dataitemEntity>().AS(tableName)
                    .WhereIF(isEnabled, x => Convert.ToBoolean(x.IsEnabled))
                    .WhereIF(!string.IsNullOrEmpty(keyword), x => x.DataItemName.Contains(keyword)
                    || x.DataItemCode.Contains(keyword))
                    .WhereIF(queryParam["UpDataItemID"] != null, x => x.UpDataItemID == queryParam["UpDataItemID"].ToString());
                if (pagination == null)
                {
                    return query.ToList();
                }
                else
                {
                    return query.ToPageList(pagination.page, pagination.rows);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_dataitemEntity GetEntity(string keyValue, string projectId)
        {
            try
            {
                return ec_dataitemService.GetEntity(keyValue, projectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取分类树形数据
        /// </summary>
        /// <returns></returns>
        public List<TreeModel> GetClassifyTree(string projectId)
        {
            try
            {
                List<ec_dataitemEntity> classifyList = (List<ec_dataitemEntity>)ec_dataitemService.GetClassifyList(projectId);
                List<TreeModel> treeList = new List<TreeModel>();
                foreach (var item in classifyList)
                {
                    TreeModel node = new TreeModel();
                    node.id = item.DataItemID;
                    node.text = item.DataItemName;
                    node.value = item.DataItemCode;
                    node.showcheck = false;
                    node.checkstate = 0;
                    node.isexpand = true;
                    node.parentId = item.UpDataItemID;
                    treeList.Add(node);
                }
                return treeList.ToTree();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 判断分类编号是否重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="dataItemCode">编码</param>
        /// <returns></returns>
        public bool ExistItemCode(string keyValue, string dataItemCode, string projectId)
        {
            try
            {
                bool res = false;
                List<ec_dataitemEntity> list = (List<ec_dataitemEntity>)ec_dataitemService.GetClassifyList(projectId);
                if (string.IsNullOrEmpty(keyValue))
                {
                    res = list.FindAll(t => t.DataItemCode.Equals(dataItemCode)).Count <= 0;
                }
                else
                {
                    res = list.FindAll(t => t.DataItemCode.Equals(dataItemCode) && !t.DataItemID.Equals(keyValue)).Count <= 0;
                }

                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 判断分类名称是否重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="dataItemName">名称</param>
        /// <returns></returns>
        public bool ExistItemName(string keyValue, string dataItemName, string projectId)
        {
            try
            {
                bool res = false;
                List<ec_dataitemEntity> list = (List<ec_dataitemEntity>)ec_dataitemService.GetClassifyList(projectId);
                if (string.IsNullOrEmpty(keyValue))
                {
                    res = list.FindAll(t => t.DataItemName.Equals(dataItemName)).Count <= 0;
                }
                else
                {
                    res = list.FindAll(t => t.DataItemName.Equals(dataItemName) && !t.DataItemID.Equals(keyValue)).Count <= 0;
                }

                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string projectId)
        {
            try
            {
                ec_dataitemService.DeleteEntity(keyValue, projectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_dataitemEntity entity, string projectId)
        {
            try
            {
                ec_dataitemService.SaveEntity(keyValue, entity, projectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 导入S3D PartNumber数据到DataItemDetail中
        /// </summary>
        /// <param name="strPartNumberItemUID"></param>
        /// <param name="strExcelFilePath"></param>
        /// <param name="projectId"></param>
        public void PartNumberDetailImport(string strPartNumberItemUID, string strExcelFilePath, string projectId)
        {
            try
            {
                ec_dataitemService.ImportPartNumberDetails(strPartNumberItemUID, strExcelFilePath, projectId);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        #endregion


        #region 字典明细
        /// <summary>
        /// 获取一个枚举下面所有的子枚举（包括自己）
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="detailId"></param>
        /// <returns></returns>
        public List<string> GetChildNodes(string projId, string detailId)
        {
            var res = new List<string>();
            var tableName = ProjectSugar.TableName<ec_dataitemdetailEntity>(projId);
            var detail = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(tableName).First(x => x.DataItemDetailID == detailId);
            if (detail != null)
            {
                res.Add(detail.DataItemDetailID);
                var allDetails = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(tableName).Where(x => x.DataItemID == detail.DataItemID)
                    .ToList();

                GetChildNodesLoop(ref res, tableName, allDetails, detail.DataItemDetailID);

                return res;
            }
            else
            {
                return res;
            }
        }
        void GetChildNodesLoop(ref List<string> res, string tableName, List<ec_dataitemdetailEntity> allDetails, string ParentId)
        {
            res.Add(ParentId);
            var childs = allDetails.Where(x => x.UpDataItemDetailID == ParentId).ToList();
            if (childs.Count == 0)
            {
                
                return;
            }
            foreach (var child in childs)
            {
                GetChildNodesLoop(ref res, tableName, allDetails, child.DataItemDetailID);
            }

        }
        /// <summary>
        /// 获取数据字典明细
        /// </summary>
        /// <param name="dataItemCode">分类编码</param>
        /// <param name="keyword">关键词（名称/值）</param>
        /// <param name="isAll">是否包含无效数据</param>
        /// <returns></returns>
        public List<ec_dataitemdetailEntity> GetDetailList(string dataItemCode, string keyword, string projectId, bool isAll = true)
        {
            try
            {
                return (List<ec_dataitemdetailEntity>)ec_dataitemService.GetDetailList(dataItemCode, keyword, projectId, isAll);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取字典明细树形数据
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <returns></returns>
        public List<TreeModel> GetDetailTree(string itemCode, string projectId)
        {
            try
            {
                var list = ec_dataitemService.GetDetailList(itemCode, string.Empty, projectId, false);
                List<TreeModel> treeList = new List<TreeModel>();
                foreach (var item in list)
                {
                    TreeModel node = new TreeModel();
                    node.id = item.DataItemDetailID;
                    node.text = item.DataItemName;
                    node.value = item.DataItemCode;
                    node.showcheck = false;
                    node.checkstate = 0;
                    node.isexpand = true;
                    node.parentId = item.UpDataItemDetailID == null ? "0" : item.UpDataItemDetailID;
                    treeList.Add(node);
                }
                return treeList.ToTree();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 字典明细编号不能重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="dataItemCode">字典明细编号</param>
        /// <param name="itemCode">分类编码</param>
        /// <returns></returns>
        public bool ExistDetailItemCode(string keyValue, string dataItemCode, string itemCode, string projectId)
        {
            try
            {
                bool res = false;
                List<ec_dataitemdetailEntity> list = GetDetailList(itemCode, "", projectId, false);

                if (string.IsNullOrEmpty(keyValue))
                {
                    res = list.FindAll(t => t.DataItemCode.Equals(dataItemCode)).Count <= 0;
                }
                else
                {
                    res = list.FindAll(t => t.DataItemCode.Equals(dataItemCode) && !t.DataItemDetailID.Equals(keyValue)).Count <= 0;
                }
                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }

        }
        /// <summary>
        /// 字典明细名称不能重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="dataItemName">字典明细名称</param>
        /// <param name="itemCode">分类编码</param>
        /// <returns></returns>
        public bool ExistDetailItemName(string keyValue, string dataItemName, string itemCode, string projectId)
        {
            try
            {
                bool res = false;
                List<ec_dataitemdetailEntity> list = GetDetailList(itemCode, "", projectId, false);

                if (string.IsNullOrEmpty(keyValue))
                {
                    res = list.FindAll(t => t.DataItemName.Equals(dataItemName)).Count <= 0;
                }
                else
                {
                    res = list.FindAll(t => t.DataItemName.Equals(dataItemName) && !t.DataItemDetailID.Equals(keyValue)).Count <= 0;
                }
                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }

        }

        /// <summary>
        /// 保存明细数据实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">实体</param>
        public string SaveDetailEntity(string keyValue, ec_dataitemdetailEntity entity, string projectId)
        {
            try
            {
                var tableName = ProjectSugar.TableName<ec_dataitemEntity>(projectId);
                var classifyEntity = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(tableName)
                    .First(x => x.DataItemID == entity.DataItemID || x.DataItemCode == entity.ItemCode);
                if (classifyEntity != null)
                {
                    if (classifyEntity.IsTree != 1 || string.IsNullOrEmpty(entity.UpDataItemDetailID))
                    {
                        entity.UpDataItemDetailID = "0";
                    }
                    entity.DataItemID = classifyEntity.DataItemID;
                    ec_dataitemService.SaveDetailEntity(keyValue, entity, projectId, out string NewID);
                    return NewID;

                }
                else
                {
                    throw new Exception("找不到数据字典分类");
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 删除明细数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void DeleteDetail(string keyValue, string projectId)
        {
            try
            {
                ec_dataitemService.DeleteDetail(keyValue, projectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion
    }
}
